<script setup lang="ts">
  import { PropType, ref } from 'vue'
  import OperateLog from './OperationLog.vue'
  import OrderReply from './OrderReply.vue'
  import { TabPaneName } from 'element-plus'
  import OrderUrgeReturn from './OrderUrgeReturn.vue'

  defineOptions({
    name: 'OrderDetailSidebar',
  })

  const props = defineProps({
    orderDetail: {
      type: Object as PropType<OrderDetail>,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'update'): void
  }>()

  // 激活的标签名
  const activeTab = ref<'orderProcess' | 'orderReply' | 'orderUrgeReturn'>('orderProcess')

  // 工单进程组件实例
  const operateLogInstance = ref<InstanceType<typeof OperateLog> | null>(null)

  // 工单回复组件实例
  const orderReplyInstance = ref<InstanceType<typeof OrderReply> | null>(null)

  // 催退组件实例
  const orderUrgeReturnInstance = ref<InstanceType<typeof OrderUrgeReturn> | null>(null)

  /**
   * 标签切换事件
   * @param tabName - 切换后的标签名
   */
  const handleTabChange = (tabName: TabPaneName) => {
    if (tabName === 'orderProcess') {
      if (operateLogInstance.value) {
        operateLogInstance.value.getList(1)
      }
    }

    if (tabName === 'orderReply') {
      if (orderReplyInstance.value) {
        orderReplyInstance.value.init()
      }
    }

    if (tabName === 'orderUrgeReturn') {
      if (orderUrgeReturnInstance.value) {
        orderUrgeReturnInstance.value.init()
      }
    }
  }

  defineExpose({
    init: () => {
      if (activeTab.value === 'orderProcess') {
        if (operateLogInstance.value) {
          operateLogInstance.value.getList(1)
        }
      }

      if (activeTab.value === 'orderReply') {
        if (orderReplyInstance.value) {
          orderReplyInstance.value.init()
        }
      }

      if (activeTab.value === 'orderUrgeReturn') {
        if (orderUrgeReturnInstance.value) {
          orderUrgeReturnInstance.value.init()
        }
      }
    },
  })
</script>

<template>
  <div class="order-detail-sidebar">
    <el-tabs v-model="activeTab" @tab-change="handleTabChange">
      <el-tab-pane label="工单进程" name="orderProcess">
        <operate-log ref="operateLogInstance" :work-id="props.orderDetail.id" />
      </el-tab-pane>
      <el-tab-pane v-permission="'fill_order_reply'" label="工作日志" name="orderReply">
        <order-reply ref="orderReplyInstance" :order-detail="props.orderDetail" />
      </el-tab-pane>
      <el-tab-pane v-permission="'urge_return'" label="催退" name="orderUrgeReturn">
        <order-urge-return
          ref="orderUrgeReturnInstance"
          :order-detail="props.orderDetail"
          @updated="emits('update')"
        />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<style scoped lang="scss">
  .order-detail-sidebar {
    height: 100%;

    :deep(.el-tabs) {
      height: 100%;

      .el-tabs__content {
        flex: 1;
        height: 0;

        .el-tab-pane {
          height: 100%;
        }
      }
    }
  }
</style>
